package com.ruoyi.web.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import com.ruoyi.common.core.domain.entity.BusinessSys;
import com.ruoyi.common.core.domain.entity.Person;
import com.ruoyi.system.service.IBusinessSysService;
import com.ruoyi.system.service.IDockingErrService;
import com.ruoyi.system.service.IPersonService;
import com.ruoyi.web.bean.VerifyResult;
import com.ruoyi.web.service.AsyncSignService;
import com.ruoyi.web.service.CQYCSignService;
import com.ruoyi.web.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * 重庆烟草签章实现
 * 异步签章
 * 签章接口需要业务系统提供回调方式
 */
@Controller
@RequestMapping(value="/cqyc/pdf")
public class PdfSignControllerCQYC {

    @Autowired
    private CQYCSignService signService;
    @Autowired
    private IBusinessSysService businessSysService;
    @Autowired
    private IPersonService personService;
    @Autowired
    private IDockingErrService dockingErrService;
    @Resource
    private AsyncSignService asyncSignService;

    /**
     * 根据关键字定位对pdf进行签章
     * @param data 签章数据
     * @return 返回结果
     */
    @RequestMapping(value ="/signPdfByKeyword")
    @ResponseBody
    public String signPdfByKeyword(String data,HttpServletRequest request) {
        return signPdf(data,request);
    }
    /**
     * 根据书签定位对pdf进行签章
     * @param data 签章数据
     * @return 返回结果
     */
    @RequestMapping(value ="/signPdfByBookmark")
    @ResponseBody
    public String signPdfByBookmark(String data,HttpServletRequest request) {
        return signPdf(data,request);
    }
    /**
     * 根据坐标定位对pdf进行签章
     * @param data 签章数据
     * @return 返回结果
     */
    @RequestMapping(value ="/signPdfByXY")
    @ResponseBody
    public String signPdfByXY(String data,HttpServletRequest request) {
        return signPdf(data,request);
    }
    /**
     * 骑缝章
     * @param data 签章数据
     * @return 返回结果
     */
    @RequestMapping(value ="/signPdfByOver")
    @ResponseBody
    public String signPdfByOver(String data,HttpServletRequest request) {
        return signPdf(data,request);
    }


    /**
     * 对签章前置参数进行检查
     * @param businessSys 业务系统ID
     * @param signUser 签章人
     * @param documentCode 文档编码
     * @return  检查结果
     */
    public JSONObject ParameterCheck(String businessSys, String signUser,String documentCode){
        JSONObject result = new JSONObject();
        //查找业务系统名称
        BusinessSys business_system  = businessSysService.selectBusinessSysByBSysId(businessSys);
        if (business_system==null){
            result.put("code","0002");
            result.put("msg","找不到业务系统");
            return result;
        }
        //查找签章人员
        Person signPer = personService.findPersonBySYS(businessSys,signUser);
        if (signPer==null){
            result.put("code","0001");
            result.put("msg","找不到签章人");
            return result;
        }
        result.put("code","0000");
        result.put("msg","参数检查通过");
        return result;
    }
    /**
     * 对接收的参数做一次补全，目的是支持两种参数形式
     * Content-Type: application/x-www-form-urlencoded  参数正文
     * Content-Type: application/json 文本正文
     * @return 参数
     */
    public String complementParam(String data,HttpServletRequest request){
        if (data ==null){
            StringBuilder data1 = new StringBuilder();
            String line ;
            BufferedReader reader ;
            try {
                reader = request.getReader();
                while (null != (line = reader.readLine())) {
                    data1.append(line);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            data = data1.toString();
        }
        return data;
    }

    /**
     * PDF文档验章接口，接口
     */
    @RequestMapping(value ="/verify")
    @ResponseBody
    public JSONArray verify(MultipartFile document) throws Exception {
        List<VerifyResult> verifyResultList =  signService.verifyPdfSign(document.getBytes());
        JSONArray jsonArray = new JSONArray();
        for (VerifyResult verifyResult :verifyResultList){
            JSONObject jsonObject =new JSONObject();
            jsonObject.put("sealName",verifyResult.getSealName());
            jsonObject.put("documentVerify",verifyResult.getDocumentVerify());
            jsonObject.put("certVerify",verifyResult.getCertVerify());
            jsonArray.add(jsonObject);
        }
        return jsonArray;
    }
    /**
     * 集合定位 签章
     * @param data 签章数据
     * @return 返回结果
     */
    @RequestMapping(value ="/signPdf")
    @ResponseBody
    public String signPdf(String data,HttpServletRequest request){
        data = complementParam(data,request);
        JSONObject result;
        //首先确认参数
        JSONObject dataJs = null;
        try{
            dataJs = JSONObject.parseObject(data);
        }catch (Exception e){
            result = new JSONObject();
            result.put("code","0001");
            result.put("msg","参数格式异常");
            return result.toJSONString();
        }
        String documentCode = dataJs.getString("documentCode");
        String signUser = dataJs.getString("signUser");
        String businessSys = dataJs.getString("businessSys");

        //默认异步调用
        boolean isAsync = false;
        if (dataJs.containsKey("isAsync")){
            isAsync = dataJs.getBoolean("isAsync");
        }
        JSONArray seals = dataJs.getJSONArray("seals");
        //检查前置参数
        result = ParameterCheck(businessSys,signUser,documentCode);
        if (!result.getString("code").equals("0000")){
            //如果签章失败添加错误日志
            dockingErrService.insertDockingErrSign(businessSys,
                    result.getString("msg")+"&code:"+result.getString("code"),"异步签章");
            return result.toJSONString();
        }
        String event ="同步签章";
        if(isAsync){
            //异步签章
            asyncSignService.asyncSignPDF(seals,documentCode,businessSys,signUser);
            result.put("code","0000");
            result.put("msg","签章任务添加成功");
            event = "异步签章";
        }else {
            //同步签章
            result = signService.signPDF(seals,documentCode,businessSys,signUser);
        }
        if (!"0000".equals(result.getString("code"))){     //查找文档
            //如果签章失败添加错误日志
            dockingErrService.insertDockingErrSign(businessSys,
                    result.getString("msg")+"&code:"+result.getString("code")+"&data:"+data,event);
        }
        return result.toJSONString();
    }
}
